# -*- coding: utf-8 -*-

# File Name： path
# Description :
# Author : ''
# create_date： 2022/5/30
# Change Activity:
"""
文件路径库封装
"""
import os


def is_absolute_path(path):
    """
    判断文件是否是绝对路径

    Args:
        path: 路径

    Returns:
        bool: 是否是绝对路径

    """
    assert path is not None and len(path) > 2
    if path[0] == '/':
        return True
    if path[1] == ':':
        return True
    return False


def check_file_exist(path):
    """
    检查文件是否存在

    Args:
        path: 文件路径

    Returns:
        bool: 文件是否存在
    """

    if not os.path.isfile(path):
        return False
    return True


def assert_file_exist(file_path):
    """
    assert 文件存在，如果文件不存在报错
    Args:
        file_path: 文件路径

    Returns:

    """
    if not check_file_exist(file_path):
        raise Exception(f'{file_path} not exist.')


def list_file_paths_in_dir(directory, suffix=None):
    """
    遍历文件夹内文件，将所有文件路径保存到list中并返回。

    Args:
        directory: 文件夹路径
        suffix: 文件后缀，如果为None，返回所有文件

    Returns:
        list: 文件路径

    """
    files_list = []
    for root, _, files in os.walk(directory, topdown=False):
        for name in files:
            if suffix is not None and not name.endswith(suffix):
                continue
            files_list.append(os.path.join(root, name))
    return files_list


def list_file_and_dir_paths_in_dir(path_dir):
    """
    返回文件路径和文件夹路径

    Args:
        path_dir: 文件夹路径

    Returns:
        list: 文件路径
    """
    file_path = []
    if os.path.exists(path_dir):
        path_dir = os.path.abspath(path_dir)
        for i in os.listdir(path_dir):
            path_i = os.path.join(path_dir, i)
            if os.path.isfile(path_i):
                file_path.append(path_i)
            else:
                file_path.extend(list_file_paths_in_dir(path_i))
    return file_path


def get_absolute_project_path():
    """
    获取项目的绝对路径

    Returns:
        project_path(str): 项目绝对路径
    """
    utility_path = get_absolute_dir(__file__)
    common_path = split_path(utility_path)[0]
    project_path = split_path(common_path)[0]
    project_path = split_path(project_path)[0]
    return project_path


def get_absolute_dir(file):
    """
    获取给定文件的绝对路径

    Args:
        file: 文件对象

    Returns:
        str: 文件的绝对路径

    """

    _path = os.path.realpath(file)
    abs_dir, _ = split_path(_path)
    return abs_dir


def join_relative_path(relative_path):
    """
    相对路径和项目的绝对路径合并

    Args:
        relative_path:

    Returns:
        str: 合成路径
    """
    relative_path = os.path.expanduser(relative_path)
    return os.path.join(get_absolute_project_path(), relative_path).replace('\\', '/')


def join_path(dir_path, file_path):
    """
    路径合成

    Args:
        dir_path: 目录
        file_path: 文件路径

    Returns:

    """

    return os.path.join(dir_path, file_path)


def create_dir(dir_path):
    """
    创建文件夹

    Args:
        dir_path: 文件夹路径

    Returns:

    """

    try:
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
    except Exception as e:
        print(e)


def split_path(path) -> [str, str]:
    """
    将路径名分割成路径名和文件名

    Args:
        path: 文件路径

    Returns:
        文件路径和文件名

    """
    dir_name, file_name = os.path.split(path)
    return dir_name, file_name


def get_file_name(path):
    """
    根据路径获取文件名

    Args:
        path: 文件路径

    Returns:
        文件名

    """
    _, name = split_path(path)
    return os.path.splitext(name)[0]


def get_file_name_suffix(file_name):
    """
    获取文件后缀

    Args:
        file_name: 文件或路径名

    Returns:
        suffix(str): 文件后缀
    """
    _items = file_name.split('.')
    if len(_items) < 1:
        raise Exception('file name is not valid.')
    _suffix = '.' + _items[-1]
    return _suffix


def delete_file(path):
    """
    删除文件

    Args:
        path: 文件名

    Returns:

    """
    try:
        os.remove(path)
    except Exception as e:
        print(e)


def delete_dir(path):
    """
    删除文件夹

    Args:
        path: 文件夹路径

    Returns:

    """

    try:
        paths = list_file_and_dir_paths_in_dir(path)
        for p in paths:
            os.remove(p)
        os.removedirs(path)
    except Exception as e:
        print(e)


def get_name_path_mapping(dir_path, include_suffix=True) -> dict:
    """
    获取文件名-路径的映射

    Args:
        dir_path: 文件夹名称
        include_suffix: 后缀

    Returns:

    """
    paths = list_file_paths_in_dir(dir_path)
    mapping = {}
    for p in paths:
        _, name = os.path.split(p)
        if not include_suffix:
            name = get_file_name(name)
        mapping[name] = p
    return mapping
